<template>
  <div class="container" id="container">
    <van-nav-bar
      :title="userInfo.regStatus == 4 ? '资料修改' : '商户入网'"
      right-text="保存"
      left-arrow
      @click-left="goBack"
      @click-right="noSave"
    />
    <div class="content-box">
      <Remarks v-if="userInfo.regStatus == 4" :contents="userInfo.remarks" />

      <!-- 步骤条 -->
      <Steps
        :dataSource="
          formData.openType != 1
            ? [
                { name: '基本信息', checked: true },
                { name: '结算信息' },
                { name: '费率信息' },
                { name: '附件信息' },
              ]
            : [{ name: '基本信息', checked: true }, { name: '附件信息' }]
        "
      />
      <van-form
        scroll-to-error
        input-align="right"
        ref="form"
        @submit="nextStep"
      >
        <van-field
          class="mt-margin"
          name="uploader"
          :rules="[{ validator, message: '请上传营业执照图片' }]"
          v-if="configEle.includes('eleLicenseImg')"
        >
          <template #label>
            <p class="attach-item-title">营业执照</p>
            <p class="placholder">请上传营业执照正面图片</p>
            <p class="example" @click="lookExample(bizImgExample)">
              查看示例&nbsp;
              <van-icon name="arrow" />
            </p>
          </template>
          <template #input>
            <UploaderImg
              v-model="bizImgList"
              @uploadAfter="uploadOpenImg"
              @beforeDelete="deleteOpenImg"
              :ocr-fun="openImgOcr"
            >
              <img class="preview-img" src="@/assets/store/biz-img.png" alt />
            </UploaderImg>
          </template>
        </van-field>
        <van-field
          v-if="configEle.includes('eleFullName')"
          class="mt-margin"
          label="商户全称"
          placeholder="请输入商户全称"
          name="merchantFullName"
          rows="1"
          type="textarea"
          v-model="formData.merchantFullName"
          autosize
          @input="change1"
          :rules="[
            { required: true, message: '请输入商户全称' },
            {
              pattern: /^[\u4e00-\u9fa5a-zA-Z0-9\(\)\（\）]{1,50}$/,
              message: '请输入小于50的中文/字母/数字组合',
            },
            {
              validator: (val) => {
                if (formData.merchantType == 2 && val.includes('公司')) {
                  return false;
                } else {
                  return true;
                }
              },
              message: '企业执照不允许选择个体工商户类型入网！',
            },
            this.$checkWordBaseFormRule,
          ]"
        />
        <van-field
          v-if="configEle.includes('eleShortName')"
          v-model="formData.merchantAbbrName"
          label="商户简称"
          @input="change2"
          rows="1"
          autosize
          type="textarea"
          name="merchantAbbrName"
          placeholder="请输入商户简称"
          :rules="[
            { required: true, message: '请输入商户简称' },
            {
              pattern: /^[\u4e00-\u9fa5a-zA-Z0-9\(\)\（\）]{3,20}$/,
              message: '请输入3-20中文/字母/数字的商户简称',
            },
            {
              validator: (val) => {
                if (formData.merchantType == 2 && val.includes('公司')) {
                  return false;
                } else {
                  return true;
                }
              },
              message: '企业执照不允许选择个体工商户类型入网！',
            },
            {
              validator: asyncValidator,
              message: '该商户简称已存在，请重新输入',
            },
            this.$checkWordBaseFormRule,
          ]"
        />
        <van-field
          v-model="formData.person"
          v-if="configEle.includes('eleLicenseLegalName')"
          label="执照法人姓名"
          placeholder="请输入执照法人姓名"
          name="person"
          @input="setPerson"
          :rules="[
            { required: true, message: '请输入执照法人姓名' },
            {
              pattern: /^[\u4E00-\u9fa5a-zA-Z\uf900-\ufa2d·s]{1,35}$/,
              message: '请输入小于35位的中文/字母组合',
            },
          ]"
        />

        <van-field
          v-if="configEle.includes('eleLicenseNo')"
          v-model="formData.bizLicense"
          label="执照编号"
          name="bizLicense"
          @input="change3"
          placeholder="请输入营业执照编号"
          :rules="[
            { required: true, message: '请输入营业执照编号' },
            {
              pattern: /^[a-zA-Z0-9-_]{1,50}$/,
              message: '请输入小于50的字母/数字组合',
              trigger: 'onChange',
            },
          ]"
        />
        <van-field
          v-if="configEle.includes('eleLicenseStart')"
          is-link
          readonly
          v-model="formData.bizStartTime"
          label="执照有效期"
          placeholder="执照开始日期"
          name="bizStartTime"
          :rules="[
            { required: true, message: '请选择执照开始日期' },
            {
              validator: validDateTime,
              message: '请选择正确的执照开始日期',
              trigger: 'onChange',
            },
          ]"
          @click="showPopup(3)"
        />
        <van-field
          v-if="configEle.includes('eleLicenseEnd')"
          is-link
          readonly
          v-model="formData.bizEndTime"
          label
          name="bizEndTime"
          placeholder="执照结束日期"
          @click="showPopup(4)"
          :rules="[
            { required: true, message: '请选择执照结束日期' },
            {
              validator: validDateTime,
              message: '请选择正确的执照结束日期',
              trigger: 'onChange',
            },
            {
              validator: ValidateBizEndTime,
              message: '结束日期不能小于开始日期',
              trigger: 'onChange',
            },
          ]"
        />
        <van-field
          v-if="configEle.includes('eleLicenseProvince')"
          readonly
          v-model="formData.bizAreaText"
          name="bizAreaText"
          label="执照省市"
          placeholder="执照经营省份、城市、地区"
          :rules="[{ required: true, message: '请选择执照省市' }]"
          @click="showPopup(7)"
        />
        <van-field
          v-if="configEle.includes('eleBusinessProvince')"
          readonly
          v-model="formData.bizAreaText"
          name="bizAreaText"
          label="经营省市"
          placeholder="经营省份、城市、地区"
          :rules="[{ required: true, message: '请选择经营省市' }]"
          @click="showPopup(7)"
        />
        <van-field
          v-if="configEle.includes('eleLicenseAddress')"
          label="详细地址"
          name="merchantAddress"
          type="textarea"
          maxlength="200"
          show-word-limit
          v-model="formData.merchantAddress"
          @input="change4"
          placeholder="执照详细经营地址，精确到xx路xx号"
          :rules="[
            { required: true, message: '请输入详细地址' },
            {
              pattern:
                /^[\u4e00-\u9fa5a-zA-Z0-9\-\_\（\）\(\)\s\:\：.。,，\#\——]{1,255}$/,
              message: '请输入中文/数字/字母的详细地址',
            },
            {
              validator: (val) => {
                if (val.length < 6) {
                  return false;
                } else {
                  return true;
                }
              },
              message: '详细地址至少6个字符',
            },
          ]"
        />
        <van-field
          v-if="configEle.includes('eleBusinessAddress')"
          label="经营详细地址"
          name="merchantAddress"
          type="textarea"
          maxlength="200"
          show-word-limit
          v-model="formData.merchantAddress"
          @input="change4"
          placeholder="经营详细地址，精确到xx路xx号"
          :rules="[
            { required: true, message: '请输入详细地址' },
            {
              pattern:
                /^[\u4e00-\u9fa5a-zA-Z0-9\-\_\（\）\(\)\s\:\：.。,，\#\——]{1,255}$/,
              message: '请输入中文/数字/字母的详细地址',
            },
            {
              validator: (val) => {
                if (val.length < 6) {
                  return false;
                } else {
                  return true;
                }
              },
              message: '详细地址至少6个字符',
            },
          ]"
        />
        <van-field
          v-if="configEle.includes('eleBusinessScope')"
          class="mt-margin"
          label="经营范围"
          name="bizScope"
          @input="change5"
          v-model="formData.bizScope"
          maxlength="250"
          :rules="[{ required: true, message: '请输入执照经营范围' }]"
          placeholder="执照经营范围"
        />
        <van-field
          v-if="configEle.includes('eleMCC')"
          is-link
          class="mt-margin"
          label="MCC"
          name="mccText"
          @click="selectMcc"
          v-model="formData.mccText"
          :rules="[{ required: true, message: '请输入选择MCC' }]"
          placeholder="MCC"
        />
        <div
          class="attach-item"
          v-if="
            configEle.includes('eleLegalIDCardFrontImg') ||
            configEle.includes('eleLegalIDCardBackImg') ||
            configEle.includes('eleLegalIDCardHandingImg')
          "
        >
          <p class="attach-item-title">法人身份证</p>
          <div class="upload-content">
            <van-field
              v-if="configEle.includes('eleLegalIDCardFrontImg')"
              class="upload-item"
              :rules="[{ validator, message: '请上传身份证人像面' }]"
              name="legalIdCardFontImg"
            >
              <template #input>
                <div class="upload-item">
                  <UploaderImg
                    v-model="legalIdCardFontImg"
                    @uploadAfter="uploadLegalIdCardFontImg"
                    @beforeDelete="deleteLegalFontImg"
                    :ocr-fun="legalIdCardOcr"
                  >
                    <img
                      class="preview-img"
                      src="@/assets/store/idCard-font.png"
                      alt
                    />
                  </UploaderImg>
                  <p class="placholder">请上传身份证人像面</p>
                  <p class="example" @click="lookExample(idFontImgExample)">
                    查看示例&nbsp;
                    <van-icon name="arrow" />
                  </p>
                </div>
              </template>
            </van-field>
            <van-field
              v-if="configEle.includes('eleLegalIDCardBackImg')"
              class="upload-item"
              :rules="[{ validator, message: '请上传身份证国徽面' }]"
              name="legalIdCardBackImg"
            >
              <template #input>
                <div class="upload-item">
                  <UploaderImg
                    v-model="legalIdCardBackImg"
                    @uploadAfter="uploadLegalIdCardBackImg"
                    @beforeDelete="deleteLegalBackImg"
                    backgroundImg="@/assets/store/idCard-back.png"
                    :ocr-fun="legalIdCardBackOcr"
                  >
                    <img
                      class="preview-img"
                      src="@/assets/store/idCard-back.png"
                      alt
                    />
                  </UploaderImg>
                  <p class="placholder">请上传身份证国徽面</p>
                  <p class="example" @click="lookExample(idBackImgExample)">
                    查看示例&nbsp;
                    <van-icon name="arrow" />
                  </p>
                </div>
              </template>
            </van-field>
            <van-field
              v-if="configEle.includes('eleLegalIDCardHandingImg')"
              class="upload-item"
              :rules="[{ validator, message: '请上传法人手持身份证照' }]"
              name="legalIdHandCardFontImg"
            >
              <template #input>
                <div class="upload-item">
                  <UploaderImg
                    v-model="legalIdHandCardFontImg"
                    @uploadAfter="uploadLegalIdHandCardFontImg"
                    @beforeDelete="deleteLegalHandFontImg"
                    backgroundImg="@/assets/store/idHand-font.png"
                  >
                    <img
                      class="preview-img"
                      src="@/assets/store/idHand-font.png"
                      alt
                    />
                  </UploaderImg>
                  <p class="placholder">请上传法人手持身份证照</p>
                  <p class="example" @click="lookExample(idHandFontImgExample)">
                    查看示例&nbsp;
                    <van-icon name="arrow" />
                  </p>
                </div>
              </template>
            </van-field>
          </div>
        </div>
        <van-field
          v-if="configEle.includes('eleLegalName')"
          class="mt-margin"
          label="法人身份证姓名"
          placeholder="请输入法人身份证姓名"
          name="legalName"
          v-model="formData.legalName"
          @input="change6"
          :rules="[
            { required: true, message: '请输入法人身份证姓名' },
            {
              pattern: /^[\u4E00-\u9fa5a-zA-Z\uf900-\ufa2d·s]{1,35}$/,
              message: '请输入小于35的中文/字母组合',
            },
            {
              validator: validatorLegalName,
              message: '营业执照法人姓名与法人身份证姓名不一致',
            },
          ]"
        />
        <van-field
          v-if="configEle.includes('eleLegalIdCardNo')"
          label="法人证件号"
          placeholder="请输入法人身份证号"
          name="legalIdcard"
          v-model="formData.legalIdcard"
          @input="change7"
          @blur="handlePersonVerify"
          :rules="[
            { required: true, message: '请输入法人身份证号' },
            {
              pattern: /^[0-9a-zA-Z]{1,18}$/,
              message: '请输入18位数字/字母组合类型',
              trigger: 'onChange',
            },
          ]"
        />
        <van-field
          v-if="configEle.includes('eleLegalIDCardStart')"
          is-link
          readonly
          v-model="formData.legalStartTime"
          label="身份证有效期"
          placeholder="证件开始日期"
          name="legalStartTime"
          :rules="[
            { required: true, message: '请输入证件开始日期' },
            {
              validator: validDateTime,
              message: '请选择正确的证件开始日期',
              trigger: 'onChange',
            },
          ]"
          @click="showPopup(5)"
        />
        <van-field
          v-if="configEle.includes('eleLegalIDCardEnd')"
          is-link
          readonly
          v-model="formData.legalEndTime"
          label
          placeholder="证件结束日期"
          name="legalEndTime"
          @click="showPopup(6)"
          :rules="[
            { required: true, message: '请输入证件结束日期' },
            {
              validator: validDateTime,
              message: '请选择正确的证件结束日期',
              trigger: 'onChange',
            },
            {
              validator: ValidateLegalEndTime,
              message: '结束日期不能小于开始日期',
              trigger: 'onChange',
            },
          ]"
        />
        <van-field
          v-if="configEle.includes('eleLegalIDCardAddress')"
          v-model="formData.legalIdcardAddress"
          @input="changeLegalIdcardAddress"
          clearable
          name="legalIdcardAddress"
          label="法人身份证地址"
          type="textarea"
          maxlength="255"
          show-word-limit
          placeholder="请输入法人身份证地址"
          :rules="[
            { required: true, message: '请输入法人身份证地址' },
            {
              pattern:
                /^[\u4e00-\u9fa5a-zA-Z0-9\-\_\（\）\(\)\s\:\：.。,，\#\——]{1,255}$/,
              message: '请输入中文/数字/字母的详细地址',
            },
            {
              validator: (val) => {
                return val.length >= 6;
              },
              message: '详细地址至少6个字符',
            },
          ]"
        />
        <div v-if="configEle.includes('eleBacisDesc')" class="notes">
          {{ eleBacisDesc.eleDefaultValue || "" }}
        </div>
        <van-button
          block
          type="info"
          color="#FFB72F"
          class="next-step-btn"
          native-type="submit"
          >下一步</van-button
        >
      </van-form>

      <!-- 以下是弹窗内容 -->

      <van-popup v-model="show3" position="bottom">
        <van-datetime-picker
          v-model="currentDate1"
          type="date"
          title="执照开始日期"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="selectTime1"
          @cancel="show3 = false"
        />
      </van-popup>
      <van-popup v-model="show4" position="bottom">
        <van-datetime-picker
          v-model="currentDate2"
          type="date"
          title="执照结束日期"
          cancel-button-text="长期"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="selectTime2"
          @cancel="longtTime1"
        />
      </van-popup>
      <van-popup v-model="show5" position="bottom">
        <van-datetime-picker
          v-model="currentDate3"
          type="date"
          title="证件开始日期"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="selectTime3"
          @cancel="show5 = false"
        />
      </van-popup>
      <van-popup v-model="show6" position="bottom">
        <van-datetime-picker
          v-model="currentDate4"
          type="date"
          title="证件结束日期"
          cancel-button-text="长期"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="selectTime4"
          @cancel="longtTime2"
        />
      </van-popup>
      <van-popup v-model="show7" position="bottom">
        <van-picker
          show-toolbar
          title="请选择地区"
          @change="onAreaChange"
          @cancel="onCancel(7)"
          @confirm="onAreaConfirm"
          :columns="areaColumns"
        />
      </van-popup>

      <van-dialog
        v-model="showExample"
        title="查看示例"
        confirmButtonText="关闭"
        confirmButtonColor="#FFB72F"
      >
        <div class="example-container">
          <img :src="exampleImg" class="example-img" />
        </div>
      </van-dialog>
    </div>
  </div>
</template>

<script>
import bizImgExample from "@/assets/store/biz-img-example.png";
import idFontImgExample from "@/assets/store/idCard-font-example.png";
import idHandFontImgExample from "@/assets/store/idHand-font-example.png";
import idBackImgExample from "@/assets/store/idCard-back-example.png";
import { bizLicenseOcr, idCardOcr } from "@/api/upload";
import { getAreaData } from "@/api/area";
import { GMTToStr } from "@/utils/tools";
import { save, reSaveStore } from "@/api/stores";
import {
  // reSaveMerchant,
  checkStoreAbbrName,
  getMerchantDetail,
  getCommonConfigByTenantId,
  isBlacklist,
} from "@/api/merchant";
export default {
  name: "Step1",
  components: {
    Remarks: () => import("@/components/Remarks"),
    Steps: () => import("@/components/steps"),
    UploaderImg: () => import("@/components/UploaderImg"),
  },
  data() {
    return {
      formData: {},
      minDate: new Date(1971, 0, 1),
      maxDate: new Date(2060, 10, 1),
      currentDate1: new Date(
        new Date().getFullYear(),
        new Date().getMonth(),
        new Date().getDate()
      ),
      currentDate2: new Date(
        new Date().getFullYear(),
        new Date().getMonth(),
        new Date().getDate()
      ),
      currentDate3: new Date(
        new Date().getFullYear(),
        new Date().getMonth(),
        new Date().getDate()
      ),
      currentDate4: new Date(
        new Date().getFullYear(),
        new Date().getMonth(),
        new Date().getDate()
      ),
      bizImgExample,
      idFontImgExample,
      idBackImgExample,
      idHandFontImgExample,
      exampleImg: "",
      showExample: false,
      validate: false,
      bizImgList: [],
      legalIdCardFontImg: [],
      legalIdCardBackImg: [],
      legalIdHandCardFontImg: [],

      areaColumns: [
        {
          values: [],
          defaultIndex: 0,
        },
        {
          values: [],
          defaultIndex: 0,
        },
        {
          values: [],
          defaultIndex: 0,
        },
      ],
      show1: false,
      show2: false,
      show3: false,
      show4: false,
      show5: false,
      show6: false,
      show7: false,

      limit: false,
      hide: false,
    };
  },
  computed: {
    userInfo() {
      return this.$store.state.user.userInfo;
    },
    merchantForm() {
      return this.$store.state.merchant;
    },
    agentInfo() {
      return this.$store.state.user.agentInfo;
    },
    Autonomy() {
      return this.$store.state.common.Autonomy;
    },
    configEle() {
      console.log(
        this.$store.state.common.config.map((item) => item.configEle)
      );
      return this.$store.state.common.config.map((item) => item.configEle);
    },
    eleBacisDesc() {
      const item = this.$store.state.common.config.find(
        (item) => item.configEle === "eleBacisDesc"
      );
      return item;
    },
  },

  created() {
    getCommonConfigByTenantId().then((v) => {
      const { microOpenDirectlyStoreFlag, microOpenDirectlyStoreNum } = v.data;
      this.limit =
        microOpenDirectlyStoreFlag == 1 && microOpenDirectlyStoreNum == 0;
    });
  },
  mounted() {
    const { bizImg, legalFontImg, legalHandFontImg, legalBackImg } =
      this.merchantForm;
    this.bizImgList = bizImg ? [{ url: bizImg }] : [];
    this.legalIdCardFontImg = legalFontImg ? [{ url: legalFontImg }] : [];
    this.legalIdHandCardFontImg = legalHandFontImg
      ? [{ url: legalHandFontImg }]
      : [];
    this.legalIdCardBackImg = legalBackImg ? [{ url: legalBackImg }] : [];

    this.getProvince("00");
    let form = this.$store.state.merchant;
    let newForm = JSON.parse(JSON.stringify(form));
    this.formData = newForm;
    if (this.formData.legalName && this.bizImgList.length) {
      if (!this.merchantForm.person) {
        this.setPerson(this.formData.legalName);
      }
    }
    if ([2, 3].includes(this.formData.merchantType)) {
      if (this.formData.merchantId) {
        getMerchantDetail(this.formData.merchantId).then((res) => {
          if (res.code == 200) {
            this.formData.merchantText = res.data.merchantFullName;
          }
        });
      }
    }
    window.scrollTo({
      left: 0,
      top: 0,
      behavior: "smooth",
    });
  },
  methods: {
    // 保存
    noSave() {
      this.$dialog
        .confirm({
          title: "商户认证",
          message: `确认是否保存资料？`,
          cancelButtonText: "取消",
          // cancelButtonColor: "#FFB72F",
          confirmButtonText: "确认",
          confirmButtonColor: "#FFB72F",
        })
        .then(() => {
          // 保存资料
          if (this.formData.openType) {
            this.$store.commit("setComplete", 0);
            this.$toast({
              type: "loading",
              message: "正在提交...",
              forbidClick: true,
              duration: 0,
            });
            save(this.$store.state)
              .then((res) => {
                // document.title = "提交成功";
                this.$toast.clear();
                if (res.code == 200) {
                  this.$toast({
                    type: "success",
                    message: "保存成功",
                    duration: 1500,
                  });
                  this.$store.dispatch("setSaved", true);
                } else {
                  this.$toast({
                    message: res.msg || "操作失败",
                    duration: 2000,
                    forbidClick: true,
                  });
                }
              })
              .catch((err) => {
                console.log(err);
                this.$toast.clear();
                // document.title = "返回APP";
              });
            // next();
          } else {
            document.title = "返回APP";
          }
        })
        .catch((err) => {
          console.log(err);
          // 取消
          // document.title = "返回APP";
          // next();
        });
    },
    validDateTime(val) {
      const reg = /^[1-9]\d{3}\/(0[1-9]|1[0-2])\/(0[1-9]|[1,2][0-9]|3[0,1])$/;
      console.log(reg.test(val));
      return val == "88888888" || reg.test(val);
    },
    ValidateLegalEndTime(val) {
      let startUTC = new Date(this.formData.legalStartTime).getTime();
      let endtUTC = new Date(val).getTime();
      if (val == "88888888") {
        return true;
      } else if (startUTC > endtUTC) {
        this.$store.commit("setLegalStartEnd", "");
        return false;
      } else {
        return true;
      }
    },
    ValidateBizEndTime(val) {
      let startUTC = new Date(this.formData.bizStartTime).getTime();
      let endtUTC = new Date(val).getTime();
      if (val == "88888888") {
        return true;
      } else if (startUTC > endtUTC) {
        this.$store.commit("setBizStartEnd", "");
        return false;
      } else {
        return true;
      }
    },
    asyncValidator(val) {
      console.log(/^[\u4e00-\u9fa5a-zA-Z0-9\(\)\（\）]{3,20}$/.test(val));
      if (/^[\u4e00-\u9fa5a-zA-Z0-9\(\)\（\）]{3,20}$/.test(val)) {
        return new Promise((resolve) => {
          checkStoreAbbrName({
            abbrName: val,
            storeNo: this.userInfo.storeNo || this.userInfo.merchantNo,
            deptId: this.userInfo.deptId,
          })
            .then((res) => {
              resolve(res.success);
            })
            .catch((err) => {
              resolve(err.success);
            });
        });
      }
    },
    validatorLegalName(val) {
      // 当执照法人没有配置时，法人此处不校验
      if (this.configEle.includes("eleLicenseLegalName")) {
        return this.formData.person === val;
      } else {
        return true;
      }
    },
    deleteOpenImg() {
      this.bizImgList = [];
      this.$store.commit("PSetBizImg", "");
    },
    deleteLegalFontImg() {
      this.legalIdCardFontImg = [];
      this.$store.commit("PSetLegalFontImg", "");
    },
    deleteLegalBackImg(file) {
      this.legalIdCardBackImg = [];
      this.$store.commit("PSetLegalBackImg", "");
    },
    change1(value) {
      if (
        !/^[\u4e00-\u9fa5a-zA-Z0-9\(\)\（\）]{1,50}$/.test(value) ||
        (value.includes("公司") && this.formData.merchantType == 2)
      ) {
        this.$store.commit("ISetMerchantFullName", ""); //商户全称
      } else {
        this.$store.commit("ISetMerchantFullName", value); //商户全称
      }
    },
    change2(value) {
      if (
        !/^[\u4e00-\u9fa5a-zA-Z0-9\(\)\（\）]{3,20}$/.test(value) ||
        (value.includes("公司") && this.formData.merchantType == 2)
      ) {
        this.$store.commit("ISetMerchantAbbrName", ""); //商户简称
      } else {
        this.asyncValidator(value).then((res) => {
          if (res) {
            this.$store.commit("ISetMerchantAbbrName", value); //商户简称
          } else {
            this.$store.commit("ISetMerchantAbbrName", ""); //商户简称
          }
        });
      }
    },
    change3(value) {
      if (!/^[\u4e00-\u9fa5a-zA-Z0-9-_]{1,50}$/.test(value)) {
        this.$store.commit("ISetBizLicense", ""); //执照编号
      } else {
        this.$store.commit("ISetBizLicense", value); //执照编号
      }
    },
    change4(value) {
      if (
        !/^[\u4e00-\u9fa5a-zA-Z0-9\-\_\（\）\(\)\s\:\：.。,，\#\——]{1,255}$/.test(
          value
        )
      ) {
        this.$store.commit("ISetMerchantAddress", ""); //详细地址
      } else {
        this.$store.commit("ISetMerchantAddress", value); //详细地址
      }
    },
    change5(value) {
      const bizScope = value.length > 250 ? value.substring(0, 250) : value;
      this.$store.commit("ISetBizScope", bizScope); //经营范围
    },
    change6(value) {
      if (!/^[\u4E00-\u9fa5a-zA-Z\uf900-\ufa2d·s]{1,35}$/.test(value)) {
        this.$store.commit("ISetLegalName", ""); //法人姓名
      } else {
        this.$store.commit("ISetLegalName", value); //法人姓名
      }
    },
    change7(value) {
      if (!/^[0-9a-zA-Z]{1,18}$/.test(value)) {
        this.$store.commit("ISetLegalIdcard", ""); //法人证件号
      } else {
        this.$store.commit("ISetLegalIdcard", value); //法人证件号
      }
    },
    // 修改法人身份证地址
    changeLegalIdcardAddress(value) {
      if (
        !/^[\u4e00-\u9fa5a-zA-Z0-9\-\_\（\）\(\)\s\:\：.。,，\#\——]{1,255}$/.test(
          value
        )
      ) {
        this.$store.commit("ISetLegalIdcardAddress", ""); //法人身份证地址
      } else {
        this.$store.commit("ISetLegalIdcardAddress", value); //法人身份证地址
      }
    },
    getProvince(parentCode) {
      getAreaData(parentCode).then((res) => {
        if (res.code == 200) {
          let data = res.data;
          let areaList = [];
          data.forEach((i) => {
            areaList.push({
              text: i.name,
              code: i.code,
              id: i.id,
            });
          });
          this.areaColumns[0].values = areaList;
          this.getCity(areaList[0].code);
        }
      });
    },
    getCity(parentCode) {
      getAreaData(parentCode).then((res) => {
        if (res.code == 200) {
          let data = res.data;
          let areaList = [];
          data.forEach((i) => {
            areaList.push({
              text: i.name,
              code: i.code,
              id: i.id,
            });
          });
          this.areaColumns[1].values = areaList;
          this.getDistric(areaList[0].code);
        }
      });
    },
    getDistric(parentCode) {
      getAreaData(parentCode).then((res) => {
        if (res.code == 200) {
          let data = res.data;
          let areaList = [];
          data.forEach((i) => {
            areaList.push({
              text: i.name,
              code: i.code,
              id: i.id,
            });
          });
          this.areaColumns[2].values = areaList;
        }
      });
    },
    //当地区选择变化时
    onAreaChange(picker, values, index) {
      if (index == 0) {
        this.getCity(values[index].code);
      } else if (index == 1) {
        this.getDistric(values[index].code);
      }
    },
    //点击确定
    onAreaConfirm(value) {
      let province = "";
      let provinceId = "";
      let city = "";
      let cityId = "";
      let district = "";
      let districtId = "";

      if (value[2] && value[2].code) {
        district = value[2].text;
        districtId = value[2].id;
      }
      if (value[1] && value[1].code) {
        city = value[1].text;
        cityId = value[1].id;
      }
      if (value[0] && value[0].code) {
        province = value[0].text;
        provinceId = value[0].id;
      }
      this.$store.commit("setBizArea", {
        bizAreaId: [provinceId, cityId, districtId],
        bizAreaText: province + city + district,
      });
      this.formData.bizAreaText = province + city + district;
      this.show7 = false;
    },
    selectTime1(value) {
      this.formData.bizStartTime = GMTToStr(value);
      this.$store.commit("setBizStartTime", GMTToStr(value));
      this.show3 = false;
    },
    selectTime2(value) {
      this.formData.bizEndTime = GMTToStr(value);
      this.$store.commit("setBizStartEnd", GMTToStr(value));
      this.show4 = false;
    },
    longtTime1() {
      this.formData.bizEndTime = "88888888";
      this.$store.commit("setBizStartEnd", "88888888");
      this.show4 = false;
    },
    selectTime3(value) {
      this.formData.legalStartTime = GMTToStr(value);
      this.$store.commit("setLegalStartTime", GMTToStr(value));
      this.show5 = false;
    },
    selectTime4(value) {
      this.formData.legalEndTime = GMTToStr(value);
      this.$store.commit("setLegalStartEnd", GMTToStr(value));
      this.show6 = false;
    },
    longtTime2() {
      this.formData.legalEndTime = "88888888";
      this.$store.commit("setLegalStartEnd", "88888888");
      this.show6 = false;
    },
    selectMcc() {
      this.$router.push({
        path: "/mcc",
      });
    },
    selectMerchant() {
      const isSend = this.formData.openType == 1 && this.limit;
      this.$router.push({
        path: "/selectmerchant",
        query: isSend ? { exceptStoreType: 3 } : null,
      });
    },
    lookExample(url) {
      this.exampleImg = url;
      this.showExample = true;
    },
    onOversize() {
      this.$toast("图片过大无法上传\n请上传10MB以内的图片！");
    },
    uploadOpenImg(imgUrl) {
      this.$store.commit("PSetBizImg", imgUrl);
    },
    openImgOcr(imgUrl) {
      return new Promise((resolve) => {
        bizLicenseOcr(imgUrl)
          .then((result) => {
            this.change1(result.name);
            this.change2(result.name);
            this.change3(result.regNum);
            this.change4(result.address);
            this.change5(result.business);
            this.setPerson(result.person);
            let period1 = result.period.replace(/年/g, "/");
            let period2 = period1.replace(/月/g, "/");
            let period3 = period2.replace(/日/g, "");
            let period5 = period3.replace(/长期/g, "88888888");
            this.$refs.form.validate("merchantFullName");
            this.$refs.form.validate("merchantAbbrName");
            this.formData.merchantFullName = result.name;
            this.formData.merchantAbbrName = result.name;
            this.formData.bizLicense = result.regNum;
            this.formData.bizStartTime = period5.split("至")[0];
            this.formData.bizEndTime = period5.split("至")[1];
            this.formData.merchantAddress = result.address;
            this.formData.bizScope = result.business;
            this.$store.commit("setBizStartTime", period5.split("至")[0]);
            this.$store.commit("setBizStartEnd", period5.split("至")[1]);
            this.$store.commit("PSetBizImg", imgUrl);
            this.bizImgList = [];
            this.bizImgList.push({ url: imgUrl });
            resolve();
          })
          .catch((error) => {
            this.$store.commit("PSetBizImg", imgUrl);
            this.bizImgList = [];
            this.bizImgList.push({ url: imgUrl });
            //   file.message = "OCR识别失败";
          });
      });
    },
    //法人手持身份证照
    uploadLegalIdHandCardFontImg(imgUrl) {
      this.$store.commit("PSetLegalHandFontImg", imgUrl);
    },
    deleteLegalHandFontImg() {
      this.legalIdHandCardFontImg = [];
      this.$store.commit("PSetLegalHandFontImg", "");
    },
    uploadLegalIdCardFontImg(imgUrl) {
      this.$store.commit("PSetLegalFontImg", imgUrl);
    },
    // 身份证正面ocr识别
    legalIdCardOcr(imgUrl) {
      return new Promise((resolve) => {
        idCardOcr(imgUrl)
          .then((result) => {
            if (!result.nation) {
              // file.message = "OCR识别失败";
              this.$store.commit("PSetLegalFontImg", imgUrl);
              this.legalIdCardFontImg = [];
              this.legalIdCardFontImg.push({
                url: imgUrl,
              });
            } else {
              this.change6(result.name);
              this.change7(result.idNum);
              this.formData.legalName = result.name;
              this.formData.legalIdcard = result.idNum;
              // 获取法人身份证地址
              this.formData.legalIdcardAddress = result.address;
              this.$store.commit("ISetLegalIdcardAddress", result.address);
              this.$store.commit("PSetLegalFontImg", imgUrl);
              this.legalIdCardFontImg = [];
              this.legalIdCardFontImg.push({
                url: imgUrl,
              });
            }
            resolve();
          })
          .catch((error) => {
            //   file.message = "OCR识别失败";
            this.$store.commit("PSetLegalFontImg", imgUrl);
            this.legalIdCardFontImg = [];
            this.legalIdCardFontImg.push({
              url: imgUrl,
            });
          });
      });
    },
    uploadLegalIdCardBackImg(imgUrl) {
      this.$store.commit("PSetLegalBackImg", imgUrl);
    },
    // 身份证反面ocr识别
    legalIdCardBackOcr(imgUrl) {
      return new Promise((resolve) => {
        idCardOcr(imgUrl)
          .then((result) => {
            if (result.nation) {
              // file.message = "OCR识别失败";
              this.$store.commit("PSetLegalBackImg", imgUrl);
              this.legalIdCardBackImg = [];
              this.legalIdCardBackImg.push({
                url: imgUrl,
              });
            } else {
              let arr = result.validDate.split("-");
              let start = arr[0].replace(/\./g, "/");
              let end =
                arr[1] == "长期" ? "88888888" : arr[1].replace(/\./g, "/");
              this.formData.legalStartTime = start;
              this.formData.legalEndTime = end;
              this.$store.commit("setLegalStartTime", start);
              this.$store.commit("setLegalStartEnd", end);
              this.$store.commit("PSetLegalBackImg", imgUrl);
              this.legalIdCardBackImg = [];
              this.legalIdCardBackImg.push({
                url: imgUrl,
              });
            }
            resolve();
          })
          .catch((error) => {
            //   file.message = "OCR识别失败";
            this.$store.commit("PSetLegalBackImg", imgUrl);
            this.legalIdCardBackImg = [];
            this.legalIdCardBackImg.push({
              url: imgUrl,
            });
          });
      });
    },
    goBack() {
      this.$router.push({
        path: "/submitInfo/step1",
      });
    },
    locationAddress() {
      this.$router.push({
        path: "/locationAddress",
      });
    },
    selectOpenTyepe(data, index) {
      this.formData.openTypeText = data.text;
      this.formData.openType = data.value;
      this.$store.commit("setOpenType", data);
      console.log(data, "data--");
      if (data.value == 3 || data.value == 1) {
        this.$store.commit("setMerchant", {
          merchantFullName: "",
          id: "",
        });
        this.formData.merchantText = "";
      }
      this.show1 = false;
    },
    selectMerchantType(data, index) {
      this.formData.merchantTypeText = data.text;
      this.formData.merchantType = data.value;
      this.$store.commit("setMerchantType", data);
      this.show2 = false;
    },
    onCancel(e) {
      this[`show${e}`] = false;
    },
    showPopup(e) {
      if (e == 4 && !this.formData.bizStartTime) {
        this.$toast("请先选择开始日期");
        return false;
      }
      if (e == 6 && !this.formData.legalStartTime) {
        this.$toast("请先选择开始日期");
        return false;
      }
      this[`show${e}`] = true;
    },
    nextStep() {
      this.$store.commit("getLangLatitude");
      this.$store.dispatch("getSystemRates");
      this.$store.dispatch("getUperAgentRates", this.agentInfo.id);
      if (this.formData.openType == 1) {
        this.$router.push({
          path: "/submitInfo/step5",
        });
      } else {
        this.$router.push({
          path: "/submitInfo/step3",
        });
      }
    },
    setPerson(val) {
      this.$store.commit("PSetPerson", val);
      this.formData.person = val;
    },
    // 身份证校验
    handlePersonVerify() {
      if (
        /^[0-9a-zA-Z]{1,18}$/.test(this.formData.legalIdcard) &&
        this.formData.legalIdcard.length == 18
      ) {
        isBlacklist(this.formData.legalIdcard).then(({ data }) => {
          if (data.isBlacklist) {
            let msg = data.consumerHotline
              ? `法人身份证号填写失败，代码1000，请联系客服${data.consumerHotline}`
              : `法人身份证号填写失败，代码1000`;
            this.$toast(msg);
          }
        });
      }
    },
    validator(val) {
      const check = val.filter((item) => item.url);
      return check.length > 0;
    },
  },
};
</script>
<style scoped lang="less">
.container {
  overflow: hidden;
}
.content-box {
  height: calc(100vh - 120px);
  overflow-y: scroll;
}

/deep/.van-field__label {
  color: #323233;
}
/deep/.van-dialog__content {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 57px 0;
}
.preview-img {
  width: 325px;
  height: 215px;
  margin: 0 16px 16px 0;
}
.next-step-btn {
  width: 80%;
  margin: 50px auto;
}
.app {
  background: #f9f9f9;
}
.content-box {
  background: #f9f9f9;
  padding-bottom: 1px;
  box-sizing: border-box;
}

.mt-margin {
  margin-top: 24px;
}
.example-container {
  padding: 0 100px;
  max-height: 60vh;
  overflow-y: scroll;
}
.example-container::-webkit-scrollbar {
  display: none;
}
.example-img {
  width: 100%;
  height: 100%;
}
.attach-item {
  margin-top: 24px;
  background: #fff;
  padding: 35px 32px;
  p.attach-item-title {
    font-size: 30px;
    font-weight: 400;
    color: #131313;
  }
}
.upload-title {
  text-align: left;
  font-size: 30px;
  font-weight: 400;
  color: #131313;
  width: calc(100vw - 64px);
}
.upload-content {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  width: calc(100vw - 64px);
  flex-wrap: wrap;
  .attach-label {
    width: 45%;
    padding-left: 5px;
  }
  .upload-item {
    width: auto;
    min-height: 220px;
    padding: 10px 0;
  }
}
.placholder {
  font-size: 28px;
  font-weight: 400;
  color: #131313;
  margin: 12px 0;
  text-align: center;
  opacity: 0.8;
}
.example {
  display: flex;
  align-items: center;
  color: #ffb72f;
  justify-content: center;
}
.notes {
  font-size: 28px;
  font-weight: 400;
  color: #131313;
  opacity: 0.7;
  padding: 24px 35px 0;
  line-height: 35px;
  white-space: pre-wrap;
}
/deep/.van-nav-bar__title {
  font-size: 36px !important;
}
/deep/ .van-nav-bar__text {
  color: #ffb72f !important;
}
/deep/ .van-nav-bar__content {
  height: 110px !important;
}
/deep/ .van-field__label {
  width: auto !important;
}
</style>
